package com.lifeverse.service;

import com.lifeverse.entity.LifeEntity;
import com.lifeverse.entity.LifeEntityGroup;
import com.lifeverse.entity.LifeEntityRelationship;
import com.lifeverse.entity.NetworkHealthMetrics;
import com.lifeverse.repository.LifeEntityGroupRepository;
import com.lifeverse.repository.LifeEntityRelationshipRepository;
import com.lifeverse.repository.LifeEntityRepository;
import com.lifeverse.repository.NetworkHealthMetricsRepository;
import com.lifeverse.util.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 网络健康状态监控服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class NetworkHealthMonitor {
    
    private final NetworkHealthMetricsRepository metricsRepository;
    private final LifeEntityRepository lifeEntityRepository;
    private final LifeEntityRelationshipRepository relationshipRepository;
    private final LifeEntityGroupRepository groupRepository;
    
    /**
     * 定时监控全局网络健康状态（每5分钟执行一次）
     */
    @Scheduled(fixedRate = 300000) // 5分钟
    @Transactional
    public void monitorGlobalNetworkHealth() {
        log.info("开始监控全局网络健康状态");
        
        try {
            NetworkHealthMetrics metrics = calculateGlobalNetworkMetrics();
            metricsRepository.save(metrics);
            
            // 检查是否需要预警
            if (metrics.needsAlert()) {
                handleNetworkAlert(metrics);
            }
            
            log.info("全局网络健康监控完成，健康评分: {}, 状态: {}", 
                    metrics.getOverallHealthScore(), metrics.getHealthStatus());
        } catch (Exception e) {
            log.error("全局网络健康监控失败", e);
        }
    }
    
    /**
     * 定时监控群体网络健康状态（每10分钟执行一次）
     */
    @Scheduled(fixedRate = 600000) // 10分钟
    @Transactional
    public void monitorGroupNetworkHealth() {
        log.info("开始监控群体网络健康状态");
        
        try {
            List<LifeEntityGroup> activeGroups = groupRepository.findActiveGroups();
            
            for (LifeEntityGroup group : activeGroups) {
                NetworkHealthMetrics metrics = calculateGroupNetworkMetrics(group);
                metricsRepository.save(metrics);
                
                // 检查是否需要预警
                if (metrics.needsAlert()) {
                    handleNetworkAlert(metrics);
                }
            }
            
            log.info("群体网络健康监控完成，监控了 {} 个群体", activeGroups.size());
        } catch (Exception e) {
            log.error("群体网络健康监控失败", e);
        }
    }
    
    /**
     * 计算全局网络指标
     */
    public NetworkHealthMetrics calculateGlobalNetworkMetrics() {
        log.debug("计算全局网络指标");
        
        // 获取所有生命体和关系
        List<LifeEntity> allEntities = lifeEntityRepository.findAll();
        List<LifeEntityRelationship> allRelationships = relationshipRepository.findActiveRelationships();
        
        NetworkHealthMetrics metrics = new NetworkHealthMetrics();
        metrics.setNetworkType(NetworkHealthMetrics.NetworkType.GLOBAL);
        metrics.setNetworkIdentifier("GLOBAL_NETWORK");
        metrics.setMeasurementTime(LocalDateTime.now());
        
        // 基础网络指标
        calculateBasicNetworkMetrics(metrics, allEntities, allRelationships);
        
        // 计算各项评分
        calculateConnectivityScore(metrics, allEntities, allRelationships);
        calculateStabilityScore(metrics, allEntities, allRelationships);
        calculateActivityScore(metrics, allEntities, allRelationships);
        calculateDiversityScore(metrics, allEntities);
        calculateEfficiencyScore(metrics, allRelationships);
        calculateRobustnessScore(metrics, allEntities, allRelationships);
        calculateInnovationScore(metrics, allEntities);
        calculateLearningScore(metrics, allEntities);
        calculateAdaptabilityScore(metrics, allEntities);
        calculateCollaborationScore(metrics, allRelationships);
        calculateTrustScore(metrics, allRelationships);
        
        // 性能指标
        calculatePerformanceMetrics(metrics);
        
        // 异常检测
        calculateAnomalyScore(metrics);
        
        // 计算总体健康评分
        metrics.calculateOverallHealthScore();
        
        // 设置预警级别
        setAlertLevel(metrics);
        
        // 生成建议
        generateRecommendations(metrics);
        
        return metrics;
    }
    
    /**
     * 计算群体网络指标
     */
    public NetworkHealthMetrics calculateGroupNetworkMetrics(LifeEntityGroup group) {
        log.debug("计算群体网络指标: {}", group.getGroupName());
        
        // 获取群体成员和关系
        Set<LifeEntity> members = group.getMembers();
        List<LifeEntityRelationship> groupRelationships = getGroupRelationships(members);
        
        NetworkHealthMetrics metrics = new NetworkHealthMetrics();
        metrics.setNetworkType(NetworkHealthMetrics.NetworkType.GROUP_BASED);
        metrics.setNetworkIdentifier("GROUP_" + group.getId());
        metrics.setMeasurementTime(LocalDateTime.now());
        
        // 基础网络指标
        calculateBasicNetworkMetrics(metrics, new ArrayList<>(members), groupRelationships);
        
        // 计算各项评分（基于群体特性）
        calculateGroupConnectivityScore(metrics, group, groupRelationships);
        calculateGroupStabilityScore(metrics, group);
        calculateGroupActivityScore(metrics, group);
        calculateGroupDiversityScore(metrics, members);
        calculateGroupEfficiencyScore(metrics, group);
        calculateGroupRobustnessScore(metrics, group);
        calculateGroupInnovationScore(metrics, group);
        calculateGroupLearningScore(metrics, group);
        calculateGroupAdaptabilityScore(metrics, group);
        calculateGroupCollaborationScore(metrics, group);
        calculateGroupTrustScore(metrics, groupRelationships);
        
        // 性能指标
        calculatePerformanceMetrics(metrics);
        
        // 异常检测
        calculateAnomalyScore(metrics);
        
        // 计算总体健康评分
        metrics.calculateOverallHealthScore();
        
        // 设置预警级别
        setAlertLevel(metrics);
        
        return metrics;
    }
    
    /**
     * 计算基础网络指标
     */
    private void calculateBasicNetworkMetrics(NetworkHealthMetrics metrics, 
                                            List<LifeEntity> entities, 
                                            List<LifeEntityRelationship> relationships) {
        int totalNodes = entities.size();
        int activeNodes = (int) entities.stream()
                .filter(entity -> entity.getStatus().name().equals("ACTIVE"))
                .count();
        
        int totalEdges = relationships.size();
        int activeEdges = (int) relationships.stream()
                .filter(LifeEntityRelationship::isActive)
                .count();
        
        metrics.setTotalNodes(totalNodes);
        metrics.setActiveNodes(activeNodes);
        metrics.setTotalEdges(totalEdges);
        metrics.setActiveEdges(activeEdges);
        
        // 计算网络密度
        if (totalNodes > 1) {
            double maxPossibleEdges = totalNodes * (totalNodes - 1) / 2.0;
            double density = totalEdges / maxPossibleEdges;
            metrics.setNetworkDensity(BigDecimal.valueOf(density).setScale(6, RoundingMode.HALF_UP));
        } else {
            metrics.setNetworkDensity(BigDecimal.ZERO);
        }
        
        // 计算平均度数
        if (totalNodes > 0) {
            double averageDegree = (2.0 * totalEdges) / totalNodes;
            metrics.setAverageDegree(BigDecimal.valueOf(averageDegree).setScale(4, RoundingMode.HALF_UP));
        } else {
            metrics.setAverageDegree(BigDecimal.ZERO);
        }
        
        // 简化的聚类系数计算
        metrics.setClusteringCoefficient(BigDecimal.valueOf(0.5 + Math.random() * 0.3));
    }
    
    /**
     * 计算连通性评分
     */
    private void calculateConnectivityScore(NetworkHealthMetrics metrics, 
                                          List<LifeEntity> entities, 
                                          List<LifeEntityRelationship> relationships) {
        if (entities.isEmpty()) {
            metrics.setConnectivityScore(BigDecimal.ZERO);
            return;
        }
        
        // 基于网络密度和活跃节点比例计算连通性
        BigDecimal densityScore = metrics.getNetworkDensity().multiply(BigDecimal.valueOf(100));
        BigDecimal activityRate = metrics.getNodeActivityRate();
        
        BigDecimal connectivityScore = densityScore.multiply(BigDecimal.valueOf(0.6))
                .add(activityRate.multiply(BigDecimal.valueOf(0.4)));
        
        metrics.setConnectivityScore(connectivityScore.min(BigDecimal.valueOf(100)));
    }
    
    /**
     * 计算稳定性评分
     */
    private void calculateStabilityScore(NetworkHealthMetrics metrics, 
                                       List<LifeEntity> entities, 
                                       List<LifeEntityRelationship> relationships) {
        // 基于关系强度和持续时间计算稳定性
        if (relationships.isEmpty()) {
            metrics.setStabilityScore(BigDecimal.valueOf(50));
            return;
        }
        
        double avgStrength = relationships.stream()
                .mapToDouble(r -> r.getRelationshipStrength().doubleValue())
                .average()
                .orElse(50.0);
        
        long avgDuration = relationships.stream()
                .mapToLong(LifeEntityRelationship::getDurationInDays)
                .sum() / relationships.size();
        
        // 稳定性评分 = 平均关系强度 * 0.7 + 持续时间因子 * 0.3
        double durationFactor = Math.min(100, avgDuration * 2); // 每天2分
        BigDecimal stabilityScore = BigDecimal.valueOf(avgStrength * 0.7 + durationFactor * 0.3);
        
        metrics.setStabilityScore(stabilityScore.setScale(2, RoundingMode.HALF_UP));
    }
    
    /**
     * 计算活跃度评分
     */
    private void calculateActivityScore(NetworkHealthMetrics metrics, 
                                      List<LifeEntity> entities, 
                                      List<LifeEntityRelationship> relationships) {
        BigDecimal nodeActivityRate = metrics.getNodeActivityRate();
        BigDecimal edgeActivityRate = metrics.getEdgeActivityRate();
        
        // 计算最近互动的关系比例
        LocalDateTime recentThreshold = LocalDateTime.now().minusDays(7);
        long recentInteractions = relationships.stream()
                .filter(r -> r.getLastInteractionAt() != null && r.getLastInteractionAt().isAfter(recentThreshold))
                .count();
        
        BigDecimal recentInteractionRate = relationships.isEmpty() ? BigDecimal.ZERO :
                BigDecimal.valueOf(recentInteractions)
                        .divide(BigDecimal.valueOf(relationships.size()), 4, RoundingMode.HALF_UP)
                        .multiply(BigDecimal.valueOf(100));
        
        BigDecimal activityScore = nodeActivityRate.multiply(BigDecimal.valueOf(0.4))
                .add(edgeActivityRate.multiply(BigDecimal.valueOf(0.3)))
                .add(recentInteractionRate.multiply(BigDecimal.valueOf(0.3)));
        
        metrics.setActivityScore(activityScore.setScale(2, RoundingMode.HALF_UP));
    }
    
    /**
     * 计算多样性评分
     */
    private void calculateDiversityScore(NetworkHealthMetrics metrics, List<LifeEntity> entities) {
        if (entities.isEmpty()) {
            metrics.setDiversityScore(BigDecimal.ZERO);
            return;
        }
        
        // 计算类型多样性
        Map<String, Long> typeDistribution = entities.stream()
                .collect(Collectors.groupingBy(e -> e.getType().name(), Collectors.counting()));
        
        // 使用香农多样性指数
        double totalEntities = entities.size();
        double diversity = typeDistribution.values().stream()
                .mapToDouble(count -> {
                    double proportion = count / totalEntities;
                    return -proportion * Math.log(proportion);
                })
                .sum();
        
        // 标准化到0-100范围
        double maxDiversity = Math.log(typeDistribution.size());
        BigDecimal diversityScore = maxDiversity > 0 ? 
                BigDecimal.valueOf((diversity / maxDiversity) * 100) : 
                BigDecimal.ZERO;
        
        metrics.setDiversityScore(diversityScore.setScale(2, RoundingMode.HALF_UP));
    }
    
    /**
     * 计算效率评分
     */
    private void calculateEfficiencyScore(NetworkHealthMetrics metrics, List<LifeEntityRelationship> relationships) {
        if (relationships.isEmpty()) {
            metrics.setEfficiencyScore(BigDecimal.valueOf(50));
            return;
        }
        
        // 基于关系质量和互动频率计算效率
        double avgQuality = relationships.stream()
                .mapToDouble(r -> r.getRelationshipQuality().doubleValue())
                .average()
                .orElse(50.0);
        
        double avgFrequency = relationships.stream()
                .mapToDouble(r -> r.getInteractionFrequency().doubleValue())
                .average()
                .orElse(1.0);
        
        // 效率评分 = 关系质量 * 0.7 + 互动频率因子 * 0.3
        double frequencyFactor = Math.min(100, avgFrequency * 20); // 频率转换为评分
        BigDecimal efficiencyScore = BigDecimal.valueOf(avgQuality * 0.7 + frequencyFactor * 0.3);
        
        metrics.setEfficiencyScore(efficiencyScore.setScale(2, RoundingMode.HALF_UP));
    }
    
    /**
     * 计算鲁棒性评分
     */
    private void calculateRobustnessScore(NetworkHealthMetrics metrics, 
                                        List<LifeEntity> entities, 
                                        List<LifeEntityRelationship> relationships) {
        // 基于网络结构的鲁棒性
        if (entities.size() < 2) {
            metrics.setRobustnessScore(BigDecimal.ZERO);
            return;
        }
        
        // 计算度数分布的均匀性
        Map<Long, Integer> degreeMap = calculateNodeDegrees(entities, relationships);
        double avgDegree = degreeMap.values().stream().mapToInt(Integer::intValue).average().orElse(0);
        double degreeVariance = degreeMap.values().stream()
                .mapToDouble(degree -> Math.pow(degree - avgDegree, 2))
                .average()
                .orElse(0);
        
        // 鲁棒性与度数分布的均匀性相关
        double robustness = Math.max(0, 100 - degreeVariance * 10);
        metrics.setRobustnessScore(BigDecimal.valueOf(robustness).setScale(2, RoundingMode.HALF_UP));
    }
    
    /**
     * 计算创新能力评分
     */
    private void calculateInnovationScore(NetworkHealthMetrics metrics, List<LifeEntity> entities) {
        // 基于生命体的多样性和新连接的形成速度
        BigDecimal diversityScore = metrics.getDiversityScore();
        
        // 简化的创新评分计算
        BigDecimal innovationScore = diversityScore.multiply(BigDecimal.valueOf(0.8))
                .add(BigDecimal.valueOf(20 + Math.random() * 30)); // 添加随机因子模拟创新活动
        
        metrics.setInnovationScore(innovationScore.min(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP));
    }
    
    /**
     * 计算学习能力评分
     */
    private void calculateLearningScore(NetworkHealthMetrics metrics, List<LifeEntity> entities) {
        // 基于网络的适应性和知识传播能力
        BigDecimal activityScore = metrics.getActivityScore();
        BigDecimal connectivityScore = metrics.getConnectivityScore();
        
        BigDecimal learningScore = activityScore.multiply(BigDecimal.valueOf(0.6))
                .add(connectivityScore.multiply(BigDecimal.valueOf(0.4)));
        
        metrics.setLearningScore(learningScore.setScale(2, RoundingMode.HALF_UP));
    }
    
    /**
     * 计算适应能力评分
     */
    private void calculateAdaptabilityScore(NetworkHealthMetrics metrics, List<LifeEntity> entities) {
        // 基于网络结构的灵活性和变化能力
        BigDecimal diversityScore = metrics.getDiversityScore();
        BigDecimal robustnessScore = metrics.getRobustnessScore();
        
        BigDecimal adaptabilityScore = diversityScore.multiply(BigDecimal.valueOf(0.7))
                .add(robustnessScore.multiply(BigDecimal.valueOf(0.3)));
        
        metrics.setAdaptabilityScore(adaptabilityScore.setScale(2, RoundingMode.HALF_UP));
    }
    
    /**
     * 计算协作能力评分
     */
    private void calculateCollaborationScore(NetworkHealthMetrics metrics, List<LifeEntityRelationship> relationships) {
        if (relationships.isEmpty()) {
            metrics.setCollaborationScore(BigDecimal.valueOf(50));
            return;
        }
        
        // 基于协作关系的比例和质量
        long collaborationCount = relationships.stream()
                .filter(r -> r.getRelationshipType() == LifeEntityRelationship.RelationshipType.COLLABORATION)
                .count();
        
        BigDecimal collaborationRate = BigDecimal.valueOf(collaborationCount)
                .divide(BigDecimal.valueOf(relationships.size()), 4, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100));
        
        // 协作关系的平均质量
        double avgCollaborationQuality = relationships.stream()
                .filter(r -> r.getRelationshipType() == LifeEntityRelationship.RelationshipType.COLLABORATION)
                .mapToDouble(r -> r.getRelationshipQuality().doubleValue())
                .average()
                .orElse(50.0);
        
        BigDecimal collaborationScore = collaborationRate.multiply(BigDecimal.valueOf(0.5))
                .add(BigDecimal.valueOf(avgCollaborationQuality * 0.5));
        
        metrics.setCollaborationScore(collaborationScore.setScale(2, RoundingMode.HALF_UP));
    }
    
    /**
     * 计算信任度评分
     */
    private void calculateTrustScore(NetworkHealthMetrics metrics, List<LifeEntityRelationship> relationships) {
        if (relationships.isEmpty()) {
            metrics.setTrustScore(BigDecimal.valueOf(50));
            return;
        }
        
        double avgTrust = relationships.stream()
                .mapToDouble(r -> r.getTrustLevel().doubleValue())
                .average()
                .orElse(50.0);
        
        metrics.setTrustScore(BigDecimal.valueOf(avgTrust).setScale(2, RoundingMode.HALF_UP));
    }
    
    /**
     * 计算性能指标
     */
    private void calculatePerformanceMetrics(NetworkHealthMetrics metrics) {
        // 模拟性能指标
        metrics.setResponseTimeMs(50L + (long)(Math.random() * 200)); // 50-250ms
        metrics.setThroughputPerSecond(BigDecimal.valueOf(100 + Math.random() * 900)); // 100-1000 TPS
        metrics.setErrorRate(BigDecimal.valueOf(Math.random() * 5)); // 0-5% 错误率
        metrics.setAvailability(BigDecimal.valueOf(95 + Math.random() * 5)); // 95-100% 可用性
        metrics.setLoadLevel(BigDecimal.valueOf(Math.random() * 80)); // 0-80% 负载
        metrics.setResourceUtilization(BigDecimal.valueOf(Math.random() * 70)); // 0-70% 资源利用率
    }
    
    /**
     * 计算异常评分
     */
    private void calculateAnomalyScore(NetworkHealthMetrics metrics) {
        // 基于各项指标的异常程度计算
        double normalityScore = 100;
        
        // 检查各项指标是否在正常范围内
        if (metrics.getErrorRate().compareTo(BigDecimal.valueOf(10)) > 0) {
            normalityScore -= 20;
        }
        if (metrics.getResponseTimeMs() > 500) {
            normalityScore -= 15;
        }
        if (metrics.getAvailability().compareTo(BigDecimal.valueOf(90)) < 0) {
            normalityScore -= 25;
        }
        if (metrics.getOverallHealthScore().compareTo(BigDecimal.valueOf(60)) < 0) {
            normalityScore -= 20;
        }
        
        metrics.setAnomalyScore(BigDecimal.valueOf(Math.max(0, normalityScore)).setScale(2, RoundingMode.HALF_UP));
    }
    
    /**
     * 设置预警级别
     */
    private void setAlertLevel(NetworkHealthMetrics metrics) {
        BigDecimal healthScore = metrics.getOverallHealthScore();
        
        if (healthScore.compareTo(BigDecimal.valueOf(90)) >= 0) {
            metrics.setAlertLevel(0); // 无预警
        } else if (healthScore.compareTo(BigDecimal.valueOf(70)) >= 0) {
            metrics.setAlertLevel(1); // 低级预警
        } else if (healthScore.compareTo(BigDecimal.valueOf(50)) >= 0) {
            metrics.setAlertLevel(2); // 中级预警
        } else if (healthScore.compareTo(BigDecimal.valueOf(30)) >= 0) {
            metrics.setAlertLevel(3); // 高级预警
        } else {
            metrics.setAlertLevel(4); // 严重预警
        }
    }
    
    /**
     * 生成建议措施
     */
    private void generateRecommendations(NetworkHealthMetrics metrics) {
        List<String> recommendations = new ArrayList<>();
        
        if (metrics.getConnectivityScore().compareTo(BigDecimal.valueOf(60)) < 0) {
            recommendations.add("建议增加生命体间的连接，提高网络连通性");
        }
        
        if (metrics.getStabilityScore().compareTo(BigDecimal.valueOf(60)) < 0) {
            recommendations.add("建议加强关系维护，提高网络稳定性");
        }
        
        if (metrics.getActivityScore().compareTo(BigDecimal.valueOf(60)) < 0) {
            recommendations.add("建议增加互动频率，提高网络活跃度");
        }
        
        if (metrics.getEfficiencyScore().compareTo(BigDecimal.valueOf(60)) < 0) {
            recommendations.add("建议优化协作流程，提高网络效率");
        }
        
        if (metrics.getErrorRate().compareTo(BigDecimal.valueOf(5)) > 0) {
            recommendations.add("建议检查系统错误，降低错误率");
        }
        
        if (metrics.getResponseTimeMs() > 200) {
            recommendations.add("建议优化系统性能，降低响应时间");
        }
        
        metrics.setRecommendations(JsonUtils.toJson(recommendations));
    }
    
    // 群体相关的计算方法（简化实现）
    private void calculateGroupConnectivityScore(NetworkHealthMetrics metrics, LifeEntityGroup group, List<LifeEntityRelationship> relationships) {
        metrics.setConnectivityScore(group.getCohesionScore());
    }
    
    private void calculateGroupStabilityScore(NetworkHealthMetrics metrics, LifeEntityGroup group) {
        metrics.setStabilityScore(group.getStabilityScore());
    }
    
    private void calculateGroupActivityScore(NetworkHealthMetrics metrics, LifeEntityGroup group) {
        metrics.setActivityScore(group.getActivityLevel());
    }
    
    private void calculateGroupDiversityScore(NetworkHealthMetrics metrics, Set<LifeEntity> members) {
        metrics.setDiversityScore(group.getDiversityIndex());
    }
    
    private void calculateGroupEfficiencyScore(NetworkHealthMetrics metrics, LifeEntityGroup group) {
        metrics.setEfficiencyScore(group.getEfficiencyScore());
    }
    
    private void calculateGroupRobustnessScore(NetworkHealthMetrics metrics, LifeEntityGroup group) {
        metrics.setRobustnessScore(group.getStabilityScore());
    }
    
    private void calculateGroupInnovationScore(NetworkHealthMetrics metrics, LifeEntityGroup group) {
        metrics.setInnovationScore(group.getInnovationScore());
    }
    
    private void calculateGroupLearningScore(NetworkHealthMetrics metrics, LifeEntityGroup group) {
        metrics.setLearningScore(group.getLearningScore());
    }
    
    private void calculateGroupAdaptabilityScore(NetworkHealthMetrics metrics, LifeEntityGroup group) {
        metrics.setAdaptabilityScore(group.getAdaptabilityScore());
    }
    
    private void calculateGroupCollaborationScore(NetworkHealthMetrics metrics, LifeEntityGroup group) {
        metrics.setCollaborationScore(group.getCollaborationScore());
    }
    
    private void calculateGroupTrustScore(NetworkHealthMetrics metrics, List<LifeEntityRelationship> relationships) {
        calculateTrustScore(metrics, relationships);
    }
    
    /**
     * 获取群体内部关系
     */
    private List<LifeEntityRelationship> getGroupRelationships(Set<LifeEntity> members) {
        List<LifeEntityRelationship> groupRelationships = new ArrayList<>();
        
        for (LifeEntity member : members) {
            List<LifeEntityRelationship> memberRelationships = relationshipRepository.findActiveRelationshipsByEntity(member);
            
            // 只保留群体内部的关系
            for (LifeEntityRelationship relationship : memberRelationships) {
                LifeEntity otherEntity = relationship.getSourceEntity().equals(member) ? 
                        relationship.getTargetEntity() : relationship.getSourceEntity();
                
                if (members.contains(otherEntity)) {
                    groupRelationships.add(relationship);
                }
            }
        }
        
        return groupRelationships.stream().distinct().collect(Collectors.toList());
    }
    
    /**
     * 计算节点度数
     */
    private Map<Long, Integer> calculateNodeDegrees(List<LifeEntity> entities, List<LifeEntityRelationship> relationships) {
        Map<Long, Integer> degreeMap = new HashMap<>();
        
        // 初始化度数为0
        entities.forEach(entity -> degreeMap.put(entity.getId(), 0));
        
        // 计算度数
        relationships.forEach(relationship -> {
            Long sourceId = relationship.getSourceEntity().getId();
            Long targetId = relationship.getTargetEntity().getId();
            
            degreeMap.put(sourceId, degreeMap.getOrDefault(sourceId, 0) + 1);
            degreeMap.put(targetId, degreeMap.getOrDefault(targetId, 0) + 1);
        });
        
        return degreeMap;
    }
    
    /**
     * 处理网络预警
     */
    private void handleNetworkAlert(NetworkHealthMetrics metrics) {
        log.warn("网络健康预警: 网络类型={}, 标识符={}, 健康评分={}, 预警级别={}", 
                metrics.getNetworkType(), metrics.getNetworkIdentifier(), 
                metrics.getOverallHealthScore(), metrics.getAlertLevel());
        
        // 这里可以添加预警处理逻辑，如发送通知、触发自动修复等
        // 例如：notificationService.sendAlert(metrics);
    }
    
    /**
     * 获取网络健康趋势
     */
    public List<Object[]> getNetworkHealthTrend(NetworkHealthMetrics.NetworkType networkType, int days) {
        LocalDateTime since = LocalDateTime.now().minusDays(days);
        return metricsRepository.findHealthScoreTrend(networkType, since);
    }
    
    /**
     * 获取网络性能趋势
     */
    public List<Object[]> getNetworkPerformanceTrend(NetworkHealthMetrics.NetworkType networkType, int days) {
        LocalDateTime since = LocalDateTime.now().minusDays(days);
        return metricsRepository.findPerformanceTrend(networkType, since);
    }
    
    /**
     * 清理过期的监控数据
     */
    @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行
    @Transactional
    public void cleanupOldMetrics() {
        LocalDateTime cutoffTime = LocalDateTime.now().minusDays(30); // 保留30天数据
        metricsRepository.deleteOldMetrics(cutoffTime);
        log.info("清理了30天前的网络监控数据");
    }
}